{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quadratic Equations\n",
    "\n",
    "Consider the following equation:\n",
    "\n",
    "\\begin{equation}y = 2(x - 1)(x + 2)\\end{equation}\n",
    "\n",
    "If you multiply out the factored ***x*** expressions, this equates to:\n",
    "\n",
    "\\begin{equation}y = 2x^{2} + 2x - 4\\end{equation}\n",
    "\n",
    "Note that the highest ordered term includes a squared variable (x<sup>2</sup>).\n",
    "\n",
    "Let's graph this equation for a range of ***x*** values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Create a dataframe with an x column containing values to plot\n",
    "df = pd.DataFrame ({'x': range(-9, 9)})\n",
    "\n",
    "# Add a y column by applying the quadratic equation to x\n",
    "df['y'] = 2*df['x']**2 + 2 *df['x'] - 4\n",
    "\n",
    "# Plot the line\n",
    "%matplotlib inline\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "plt.plot(df.x, df.y, color=\"grey\")\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('y')\n",
    "plt.grid()\n",
    "plt.axhline()\n",
    "plt.axvline()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the graph shows a *parabola*, which is an arc-shaped line that reflects the x and y values calculated for the equation.\n",
    "\n",
    "Now let's look at another equation that includes an ***x<sup>2</sup>*** term:\n",
    "\n",
    "\\begin{equation}y = -2x^{2} + 6x + 7\\end{equation}\n",
    "\n",
    "What does that look like as a graph?:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Create a dataframe with an x column containing values to plot\n",
    "df = pd.DataFrame ({'x': range(-8, 12)})\n",
    "\n",
    "# Add a y column by applying the quadratic equation to x\n",
    "df['y'] = -2*df['x']**2 + 6*df['x'] + 7\n",
    "\n",
    "# Plot the line\n",
    "%matplotlib inline\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "plt.plot(df.x, df.y, color=\"grey\")\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('y')\n",
    "plt.grid()\n",
    "plt.axhline()\n",
    "plt.axvline()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Again, the graph shows a parabola, but this time instead of being open at the top, the parabola is open at the bottom.\n",
    "\n",
    "Equations that assign a value to ***y*** based on an expression that includes a squared value for ***x*** create parabolas. If the relationship between ***y*** and ***x*** is such that ***y*** is a *positive* multiple of the ***x<sup>2</sup>*** term, the parabola will be open at the top; when ***y*** is a *negative* multiple of the ***x<sup>2</sup>*** term, then the parabola will be open at the bottom.\n",
    "\n",
    "These kinds of equations are known as *quadratic* equations, and they have some interesting characteristics. There are several ways quadratic equations can be written, but the *standard form* for quadratic equation is:\n",
    "\n",
    "\\begin{equation}y = ax^{2} + bx + c\\end{equation}\n",
    "\n",
    "Where ***a***, ***b***, and ***c*** are numeric coefficients or constants.\n",
    "\n",
    "Let's start by examining the parabolas generated by quadratic equations in more detail.\n",
    "\n",
    "## Parabola Vertex and Line of Symmetry\n",
    "Parabolas are symmetrical, with x and y values converging exponentially towards the highest point (in the case of a downward opening parabola) or lowest point (in the case of an upward opening parabola). The point where the parabola meets the line of symmetry is known as the *vertex*.\n",
    "\n",
    "Run the following cell to see the line of symmetry and vertex for the two parabolas described previously (don't worry about the calculations used to find the line of symmetry and vertex - we'll explore that later):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "def plot_parabola(a, b, c):\n",
    "    import pandas as pd\n",
    "    import numpy as np\n",
    "    from matplotlib import pyplot as plt\n",
    "    \n",
    "    # get the x value for the line of symmetry\n",
    "    vx = (-1*b)/(2*a)\n",
    "    \n",
    "    # get the y value when x is at the line of symmetry\n",
    "    vy = a*vx**2 + b*vx + c\n",
    "\n",
    "    # Create a dataframe with an x column containing values from x-10 to x+10\n",
    "    minx = int(vx - 10)\n",
    "    maxx = int(vx + 11)\n",
    "    df = pd.DataFrame ({'x': range(minx, maxx)})\n",
    "\n",
    "    # Add a y column by applying the quadratic equation to x\n",
    "    df['y'] = a*df['x']**2 + b *df['x'] + c\n",
    "\n",
    "    # get min and max y values\n",
    "    miny = df.y.min()\n",
    "    maxy = df.y.max()\n",
    "\n",
    "    # Plot the line\n",
    "    plt.plot(df.x, df.y, color=\"grey\")\n",
    "    plt.xlabel('x')\n",
    "    plt.ylabel('y')\n",
    "    plt.grid()\n",
    "    plt.axhline()\n",
    "    plt.axvline()\n",
    "\n",
    "    # plot the line of symmetry\n",
    "    sx = [vx, vx]\n",
    "    sy = [miny, maxy]\n",
    "    plt.plot(sx,sy, color='magenta')\n",
    "\n",
    "    # Annotate the vertex\n",
    "    plt.scatter(vx,vy, color=\"red\")\n",
    "    plt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy + 5)* np.sign(a)))\n",
    "\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "plot_parabola(2, 2, -4)   \n",
    "\n",
    "plot_parabola(-2, 3, 5) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parabola Intercepts\n",
    "Recall that linear equations create lines that intersect the **x** and **y** axis of a graph, and we call the points where these intersections occur *intercepts*. Now look at the graphs of the parabolas we've worked with so far. Note that these parabolas both have a y-intercept; a point where the line intersects the y axis of the graph (in other words, when x is 0). However, note that the parabolas have *two* x-intercepts; in other words there are two points at which the line crosses the x axis (and y is 0). Additionally, imagine a downward opening parabola with its vertex at -1, -1. This is perfectly possible, and the line would never have an x value greater than -1, so it would have *no* x-intercepts.\n",
    "\n",
    "Regardless of whether the parabola crosses the x axis or not, other than the vertex, for every ***y*** point in the parabola, there are *two* ***x*** points; one on the right (or positive) side of the axis of symmetry, and one of the left (or negative) side. The implications of this are what make quadratic equations so interesting. When we solve the equation for ***x***, there are *two* correct answers.\n",
    "\n",
    "Let's take a look at an example to demonstrate this. Let's return to the first of our quadratic equations, and we'll look at it in its *factored* form:\n",
    "\n",
    "\\begin{equation}y = 2(x - 1)(x + 2)\\end{equation}\n",
    "\n",
    "Now, let's solve this equation for a ***y*** value of 0. We can restate the equation like this:\n",
    "\n",
    "\\begin{equation}2(x - 1)(x + 2) = 0\\end{equation}\n",
    "\n",
    "The equation is the product of two expressions **2(x - 1)** and **(x + 2)**. In this case, we know that the product of these expressions is 0, so logically *one or both of the expressions must return 0*.\n",
    "\n",
    "Let's try the first one:\n",
    "\n",
    "\\begin{equation}2(x - 1) = 0\\end{equation}\n",
    "\n",
    "If we distrbute this, we get:\n",
    "\n",
    "\\begin{equation}2x - 2 = 0\\end{equation}\n",
    "\n",
    "This simplifies to:\n",
    "\n",
    "\\begin{equation}2x = 2\\end{equation}\n",
    "\n",
    "Which gives us a value for *x* of **1**.\n",
    "\n",
    "Now let's try the other expression:\n",
    "\n",
    "\\begin{equation}x + 2 = 0\\end{equation}\n",
    "\n",
    "This gives us a value for *x* of **-2**.\n",
    "\n",
    "So, when *y* is **0**, *x* is **-2** or **1**. Let's plot these points on our parabola:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# Assign the calculated x values\n",
    "x1 = -2\n",
    "x2 = 1\n",
    "\n",
    "# Create a dataframe with an x column containing some values to plot\n",
    "df = pd.DataFrame ({'x': range(x1-5, x2+6)})\n",
    "\n",
    "# Add a y column by applying the quadratic equation to x\n",
    "df['y'] = 2*(df['x'] - 1) * (df['x'] + 2)\n",
    "\n",
    "# Get x at the line of symmetry (halfway between x1 and x2)\n",
    "vx = (x1 + x2) / 2\n",
    "\n",
    "# Get y when x is at the line of symmetry\n",
    "vy = 2*(vx -1)*(vx + 2)\n",
    "\n",
    "# get min and max y values\n",
    "miny = df.y.min()\n",
    "maxy = df.y.max()\n",
    "\n",
    "# Plot the line\n",
    "%matplotlib inline\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "plt.plot(df.x, df.y, color=\"grey\")\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('y')\n",
    "plt.grid()\n",
    "plt.axhline()\n",
    "plt.axvline()\n",
    "\n",
    "# Plot calculated x values for y = 0\n",
    "plt.scatter([x1,x2],[0,0], color=\"green\")\n",
    "plt.annotate('x1',(x1, 0))\n",
    "plt.annotate('x2',(x2, 0))\n",
    "\n",
    "# plot the line of symmetry\n",
    "sx = [vx, vx]\n",
    "sy = [miny, maxy]\n",
    "plt.plot(sx,sy, color='magenta')\n",
    "\n",
    "# Annotate the vertex\n",
    "plt.scatter(vx,vy, color=\"red\")\n",
    "plt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy - 5)))\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So from the plot, we can see that both of the values we calculated for ***x*** align with the parabola when ***y*** is 0. Additionally, because the parabola is symmetrical, we know that every pair of ***x*** values for each ***y*** value will be equidistant from the line of symmetry, so we can calculate the ***x*** value for the line of symmetry as the average of the ***x*** values for any value of ***y***. This in turn means that we know the ***x*** coordinate for the vertex (it's on the line of symmetry), and we can use the quadratic equation to calculate ***y*** for this point."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Solving Quadratics Using the Square Root Method\n",
    "The technique we just looked at makes it easy to calculate the two possible values for ***x*** when ***y*** is 0 if the equation is presented as the product two expressions. If the equation is in standard form, and it can be factored, you could do the necessary manipulation to restate it as the product of two expressions. Otherwise, you can calculate the possible values for x by applying a different method that takes advantage of the relationship between squared values and the square root.\n",
    "\n",
    "Let's consider this equation:\n",
    "\n",
    "\\begin{equation}y = 3x^{2} - 12\\end{equation}\n",
    "\n",
    "Note that this is in the standard quadratic form, but there is no *b* term; in other words, there's no term that contains a coeffecient for  ***x*** to the first power. This type of equation can be easily solved using the square root method. Let's restate it so we're solving for ***x*** when ***y*** is 0:\n",
    "\n",
    "\\begin{equation}3x^{2} - 12 = 0\\end{equation}\n",
    "\n",
    "The first thing we need to do is to isolate the ***x<sup>2</sup>*** term, so we'll remove the constant on the left by adding 12 to both sides:\n",
    "\n",
    "\\begin{equation}3x^{2} = 12\\end{equation}\n",
    "\n",
    "Then we'll divide both sides by 3 to isolate x<sup>2</sup>:\n",
    "\n",
    "\\begin{equation}x^{2} = 4\\end{equation}\n",
    "\n",
    "No we can isolate ***x*** by taking the square root of both sides. However, there's an additional consideration because this is a quadratic equation. The ***x*** variable can have two possibe values, so we must calculate the *principle* and *negative* square roots of the expression on the right:\n",
    "\n",
    "\\begin{equation}x = \\pm\\sqrt{4}\\end{equation}\n",
    "\n",
    "The principle square root of 4 is 2 (because 2<sup>2</sup> is 4), and the corresponding negative root is -2 (because -2<sup>2</sup> is also 4); so *x* is **2** or **-2**.\n",
    "\n",
    "Let's see this in Python, and use the results to calculate and plot the parabola with its line of symmetry and vertex:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import math\n",
    "\n",
    "y = 0\n",
    "x1 = int(- math.sqrt(y + 12 / 3))\n",
    "x2 = int(math.sqrt(y + 12 / 3))\n",
    "\n",
    "# Create a dataframe with an x column containing some values to plot\n",
    "df = pd.DataFrame ({'x': range(x1-10, x2+11)})\n",
    "\n",
    "# Add a y column by applying the quadratic equation to x\n",
    "df['y'] = 3*df['x']**2 - 12\n",
    "\n",
    "# Get x at the line of symmetry (halfway between x1 and x2)\n",
    "vx = (x1 + x2) / 2\n",
    "\n",
    "# Get y when x is at the line of symmetry\n",
    "vy = 3*vx**2 - 12\n",
    "\n",
    "# get min and max y values\n",
    "miny = df.y.min()\n",
    "maxy = df.y.max()\n",
    "\n",
    "# Plot the line\n",
    "%matplotlib inline\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "plt.plot(df.x, df.y, color=\"grey\")\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('y')\n",
    "plt.grid()\n",
    "plt.axhline()\n",
    "plt.axvline()\n",
    "\n",
    "# Plot calculated x values for y = 0\n",
    "plt.scatter([x1,x2],[0,0], color=\"green\")\n",
    "plt.annotate('x1',(x1, 0))\n",
    "plt.annotate('x2',(x2, 0))\n",
    "\n",
    "# plot the line of symmetry\n",
    "sx = [vx, vx]\n",
    "sy = [miny, maxy]\n",
    "plt.plot(sx,sy, color='magenta')\n",
    "\n",
    "# Annotate the vertex\n",
    "plt.scatter(vx,vy, color=\"red\")\n",
    "plt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy - 20)))\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Solving Quadratics Using the Completing the Square Method\n",
    "In quadratic equations where there is a *b* term; that is, a term containing **x** to the first power, it is impossible to directly calculate the square root. However, with some algebraic manipulation, you can take advantage of the ability to factor a polynomial expression in the form *a<sup>2</sup> + 2ab + b<sup>2</sup>* as a binomial *perfect square* expression in the form *(a + b)<sup>2</sup>*.\n",
    "\n",
    "At first this might seem like some sort of mathematical sleight of hand, but follow through the steps carefull and you'll see that there's nothing up my sleeve!\n",
    "\n",
    "The underlying basis of this approach is that a trinomial expression like this:\n",
    "\n",
    "\\begin{equation}x^{2} + 24x + 12^{2}\\end{equation}\n",
    "\n",
    "Can be factored to this:\n",
    "\n",
    "\\begin{equation}(x + 12)^{2}\\end{equation}\n",
    "\n",
    "OK, so how does this help us solve a quadratic equation? Well, let's look at an example:\n",
    "\n",
    "\\begin{equation}y = x^{2} + 6x - 7\\end{equation}\n",
    "\n",
    "Let's start as we've always done so far by restating the equation to solve ***x*** for a ***y*** value of 0:\n",
    "\n",
    "\\begin{equation}x^{2} + 6x - 7 = 0\\end{equation}\n",
    "\n",
    "Now we can move the constant term to the right by adding 7 to both sides:\n",
    "\n",
    "\\begin{equation}x^{2} + 6x = 7\\end{equation}\n",
    "\n",
    "OK, now let's look at the expression on the left: *x<sup>2</sup> + 6x*. We can't take the square root of this, but we can turn it into a trinomial that will factor into a perfect square by adding a squared constant. The question is, what should that constant be? Well, we know that we're looking for an expression like *x<sup>2</sup> + 2**c**x + **c**<sup>2</sup>*, so our constant **c** is half of the coefficient we currently have for ***x***. This is **6**, making our constant **3**, which when squared is **9** So we can create a trinomial expression that will easily factor to a perfect square by adding 9; giving us the expression *x<sup>2</sup> + 6x + 9*.\n",
    "\n",
    "However, we can't just add something to one side without also adding it to the other, so our equation becomes:\n",
    "\n",
    "\\begin{equation}x^{2} + 6x + 9 = 16\\end{equation}\n",
    "\n",
    "So, how does that help? Well, we can now factor the trinomial expression as a perfect square binomial expression:\n",
    "\n",
    "\\begin{equation}(x + 3)^{2} = 16\\end{equation}\n",
    "\n",
    "And now, we can use the square root method to find x + 3:\n",
    "\n",
    "\\begin{equation}x + 3 =\\pm\\sqrt{16}\\end{equation}\n",
    "\n",
    "So, x + 3 is **-4** or **4**. We isolate ***x*** by subtracting 3 from both sides, so ***x*** is **-7** or **1**:\n",
    "\n",
    "\\begin{equation}x = -7, 1\\end{equation}\n",
    "\n",
    "Let's see what the parabola for this equation looks like in Python:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import math\n",
    "\n",
    "x1 = int(- math.sqrt(16) - 3)\n",
    "x2 = int(math.sqrt(16) - 3)\n",
    "\n",
    "# Create a dataframe with an x column containing some values to plot\n",
    "df = pd.DataFrame ({'x': range(x1-10, x2+11)})\n",
    "\n",
    "# Add a y column by applying the quadratic equation to x\n",
    "df['y'] = ((df['x'] + 3)**2) - 16\n",
    "\n",
    "# Get x at the line of symmetry (halfway between x1 and x2)\n",
    "vx = (x1 + x2) / 2\n",
    "\n",
    "# Get y when x is at the line of symmetry\n",
    "vy = ((vx + 3)**2) - 16\n",
    "\n",
    "# get min and max y values\n",
    "miny = df.y.min()\n",
    "maxy = df.y.max()\n",
    "\n",
    "# Plot the line\n",
    "%matplotlib inline\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "plt.plot(df.x, df.y, color=\"grey\")\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('y')\n",
    "plt.grid()\n",
    "plt.axhline()\n",
    "plt.axvline()\n",
    "\n",
    "# Plot calculated x values for y = 0\n",
    "plt.scatter([x1,x2],[0,0], color=\"green\")\n",
    "plt.annotate('x1',(x1, 0))\n",
    "plt.annotate('x2',(x2, 0))\n",
    "\n",
    "# plot the line of symmetry\n",
    "sx = [vx, vx]\n",
    "sy = [miny, maxy]\n",
    "plt.plot(sx,sy, color='magenta')\n",
    "\n",
    "# Annotate the vertex\n",
    "plt.scatter(vx,vy, color=\"red\")\n",
    "plt.annotate('vertex',(vx, vy), xytext=(vx - 1, (vy - 10)))\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Vertex Form\n",
    "Let's look at another example of a quadratic equation in standard form:\n",
    "\n",
    "\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n",
    "\n",
    "We can start to solve this by subtracting 2 from both sides to move the constant term from the right to the left:\n",
    "\n",
    "\\begin{equation}y - 2 = 2x^{2} - 16x\\end{equation}\n",
    "\n",
    "Now we can factor out the coefficient for x<sup>2</sup>, which is **2**. 2x<sup>2</sup> is 2 &bull; x<sup>2</sup>, and -16x is 2 &bull; 8x:\n",
    "\n",
    "\\begin{equation}y - 2 = 2(x^{2} - 8x)\\end{equation}\n",
    "\n",
    "Now we're ready to complete the square, so we add the square of half of the -8x coefficient on the right side to the parenthesis. Half of -8 is -4, and -4<sup>2</sup> is 16, so the right side of the equation becomes *2(x<sup>2</sup> - 8x + 16)*. Of course, we can't add something to one side of the equation without also adding it to the other side, and we've just added 2 &bull; 16 (which is 32) to the right, so we must also add that to the left.\n",
    "\n",
    "\\begin{equation}y - 2 + 32 = 2(x^{2} - 8x + 16)\\end{equation}\n",
    "\n",
    "Now we can simplify the left and factor out a perfect square binomial expression on the right:\n",
    "\n",
    "\\begin{equation}y + 30 = 2(x - 4)^{2}\\end{equation}\n",
    "\n",
    "We now have a squared term for ***x***, so we could use the square root method to solve the equation. However, we can also isolate ***y*** by subtracting 30 from both sides. So we end up restating the original equation as:\n",
    "\n",
    "\\begin{equation}y = 2(x - 4)^{2} - 30\\end{equation}\n",
    "\n",
    "Let's just quickly check our math with Python:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from random import randint\n",
    "x = randint(1,100)\n",
    "\n",
    "2*x**2 - 16*x + 2 == 2*(x - 4)**2 - 30"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So we've managed to take the expression ***2x<sup>2</sup> - 16x + 2*** and change it to ***2(x - 4)<sup>2</sup> - 30***. How does that help?\n",
    "\n",
    "Well, when a quadratic equation is stated this way, it's in *vertex form*, which is generically described as:\n",
    "\n",
    "\\begin{equation}y = a(x - h)^{2} + k\\end{equation}\n",
    "\n",
    "The neat thing about this form of the equation is that it tells us the coordinates of the vertex - it's at ***h,k***.\n",
    "\n",
    "So in this case, we know that the vertex of our equation is 4, -30. Moreover, we know that the line of symmetry is at ***x = 4***.\n",
    "\n",
    "We can then just use the equation to calculate two more points, and the three points will be enough for us to determine the shape of the parabola. We can simply choose any ***x*** value we like and substitute it into the equation to calculate the corresponding ***y*** value. For example, let's calculate ***y*** when x is **0**:\n",
    "\n",
    "\\begin{equation}y = 2(0 - 4)^{2} - 30\\end{equation}\n",
    "\n",
    "When we work through the equation, it gives us the answer **2**, so we know that the point 0, 2 is in our parabola.\n",
    "\n",
    "So, we know that the line of symmetry is at ***x = h*** (which is 4), and we now know that the ***y*** value when ***x*** is 0 (***h*** - ***h***) is 2. The ***y*** value at the same distance from the line of symmetry in the negative direction will be the same as the value in the positive direction, so when ***x*** is ***h*** + ***h***, the ***y*** value will also be 2.\n",
    "\n",
    "The following Python code encapulates all of this in a function that draws and annotates a parabola using only the ***a***, ***h***, and ***k*** values from a quadratic equation in vertex form:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_parabola_from_vertex_form(a, h, k):\n",
    "    import pandas as pd\n",
    "    import math\n",
    "\n",
    "    # Create a dataframe with an x column a range of x values to plot\n",
    "    df = pd.DataFrame ({'x': range(h-10, h+11)})\n",
    "\n",
    "    # Add a y column by applying the quadratic equation to x\n",
    "    df['y'] = (a*(df['x'] - h)**2) + k\n",
    "\n",
    "    # get min and max y values\n",
    "    miny = df.y.min()\n",
    "    maxy = df.y.max()\n",
    "\n",
    "    # calculate y when x is 0 (h+-h)\n",
    "    y = a*(0 - h)**2 + k\n",
    "\n",
    "    # Plot the line\n",
    "    %matplotlib inline\n",
    "    from matplotlib import pyplot as plt\n",
    "\n",
    "    plt.plot(df.x, df.y, color=\"grey\")\n",
    "    plt.xlabel('x')\n",
    "    plt.ylabel('y')\n",
    "    plt.grid()\n",
    "    plt.axhline()\n",
    "    plt.axvline()\n",
    "\n",
    "    # Plot calculated y values for x = 0 (h-h and h+h)\n",
    "    plt.scatter([h-h, h+h],[y,y], color=\"green\")\n",
    "    plt.annotate(str(h-h) + ',' + str(y),(h-h, y))\n",
    "    plt.annotate(str(h+h) + ',' + str(y),(h+h, y))\n",
    "\n",
    "    # plot the line of symmetry (x = h)\n",
    "    sx = [h, h]\n",
    "    sy = [miny, maxy]\n",
    "    plt.plot(sx,sy, color='magenta')\n",
    "\n",
    "    # Annotate the vertex (h,k)\n",
    "    plt.scatter(h,k, color=\"red\")\n",
    "    plt.annotate('v=' + str(h) + ',' + str(k),(h, k), xytext=(h - 1, (k - 10)))\n",
    "\n",
    "    plt.show()\n",
    "\n",
    "    \n",
    "# Call the function for the example discussed above\n",
    "plot_parabola_from_vertex_form(2, 4, -30)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It's important to note that the vertex form specifically requires a *subtraction* operation in the factored perfect square term. For example, consider the following equation in the standard form:\n",
    "\n",
    "\\begin{equation}y = 3x^{2} + 6x + 2\\end{equation}\n",
    "\n",
    "The steps to solve this are:\n",
    "1. Move the constant to the left side:\n",
    "\\begin{equation}y - 2 = 3x^{2} + 6x\\end{equation}\n",
    "2. Factor the ***x*** expressions on the right:\n",
    "\\begin{equation}y - 2 = 3(x^{2} + 2x)\\end{equation}\n",
    "3. Add the square of half the x coefficient to the right, and the corresponding multiple on the left:\n",
    "\\begin{equation}y - 2 + 3 = 3(x^{2} + 2x + 1)\\end{equation}\n",
    "4. Factor out a perfect square binomial:\n",
    "\\begin{equation}y + 1 = 3(x + 1)^{2}\\end{equation}\n",
    "5. Move the constant back to the right side:\n",
    "\\begin{equation}y = 3(x + 1)^{2} - 1\\end{equation}\n",
    "\n",
    "To express this in vertex form, we need to convert the addition in the parenthesis to a subtraction:\n",
    "\n",
    "\\begin{equation}y = 3(x - -1)^{2} - 1\\end{equation}\n",
    "\n",
    "Now, we can use the a, h, and k values to define a parabola:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_parabola_from_vertex_form(3, -1, -1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Shortcuts for Solving Quadratic Equations\n",
    "We've spent some time in this notebook discussing how to solve quadratic equations to determine the vertex of a parabola and the ***x*** values in relation to ***y***. It's important to understand the techniques we've used, which incude:\n",
    "- Factoring\n",
    "- Calculating the Square Root\n",
    "- Completing the Square\n",
    "- Using the vertex form of the equation\n",
    "\n",
    "The underlying algebra for all of these techniques is the same, and this consistent algebra results in some shortcuts that you can memorize to make it easier to solve quadratic equations without going through all of the steps:\n",
    "\n",
    "### Calculating the Vertex from Standard Form\n",
    "You've already seen that converting a quadratic equation to the vertex form makes it easy to identify the vertex coordinates, as they're encoded as ***h*** and ***k*** in the equation itself - like this:\n",
    "\n",
    "\\begin{equation}y = a(x - \\textbf{h})^{2} + \\textbf{k}\\end{equation}\n",
    "\n",
    "However, what if you have an equation in standard form?:\n",
    "\n",
    "\\begin{equation}y = ax^{2} + bx + c\\end{equation}\n",
    "\n",
    "There's a quick and easy technique you can apply to get the vertex coordinates. \n",
    "\n",
    "1. To find ***h*** (which is the x-coordinate of the vertex), apply the following formula:\n",
    "\\begin{equation}h = \\frac{-b}{2a}\\end{equation}\n",
    "2. After you've found ***h***, use it in the quadratic equation to solve for ***k***:\n",
    "\\begin{equation}\\textbf{k} = a\\textbf{h}^{2} + b\\textbf{h} + c\\end{equation}\n",
    "\n",
    "For example, here's the quadratic equation in standard form that we previously converted to the vertex form:\n",
    "\n",
    "\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n",
    "\n",
    "To find ***h***, we perform the following calculation:\n",
    "\n",
    "\\begin{equation}h = \\frac{-b}{2a}\\;\\;\\;\\;=\\;\\;\\;\\;\\frac{-1 \\cdot16}{2\\cdot2}\\;\\;\\;\\;=\\;\\;\\;\\;\\frac{16}{4}\\;\\;\\;\\;=\\;\\;\\;\\;4\\end{equation}\n",
    "\n",
    "Then we simply plug the value we've obtained for ***h*** into the quadratic equation in order to find ***k***:\n",
    "\n",
    "\\begin{equation}k = 2\\cdot(4^{2}) - 16\\cdot4 + 2\\;\\;\\;\\;=\\;\\;\\;\\;32 - 64 + 2\\;\\;\\;\\;=\\;\\;\\;\\;-30\\end{equation}\n",
    "\n",
    "Note that a vertex at 4,-30 is also what we previously calculated for the vertex form of the same equation:\n",
    "\n",
    "\\begin{equation}y = 2(x - 4)^{2} - 30\\end{equation}\n",
    "\n",
    "### The Quadratic Formula\n",
    "Another useful formula to remember is the *quadratic formula*, which makes it easy to calculate values for ***x*** when ***y*** is **0**; or in other words:\n",
    "\n",
    "\\begin{equation}ax^{2} + bx + c = 0\\end{equation}\n",
    "\n",
    "Here's the formula:\n",
    "\n",
    "\\begin{equation}x = \\frac{-b \\pm \\sqrt{b^{2} - 4ac}}{2a}\\end{equation}\n",
    "\n",
    "Let's apply that formula to our equation, which you may remember looks like this:\n",
    "\n",
    "\\begin{equation}y = 2x^{2} - 16x + 2\\end{equation}\n",
    "\n",
    "OK, let's plug the ***a***, ***b***, and ***c*** variables from our equation into the quadratic formula:\n",
    "\n",
    "\\begin{equation}x = \\frac{--16 \\pm \\sqrt{-16^{2} - 4\\cdot2\\cdot2}}{2\\cdot2}\\end{equation}\n",
    "\n",
    "This simplifes to:\n",
    "\n",
    "\\begin{equation}x = \\frac{16 \\pm \\sqrt{256 - 16}}{4}\\end{equation}\n",
    "\n",
    "This in turn (with the help of a calculator) simplifies to:\n",
    "\n",
    "\\begin{equation}x = \\frac{16 \\pm 15.491933384829668}{4}\\end{equation}\n",
    "\n",
    "So our positive value for ***x*** is:\n",
    "\n",
    "\\begin{equation}x = \\frac{16 + 15.491933384829668}{4}\\;\\;\\;\\;=7.872983346207417\\end{equation}\n",
    "\n",
    "And the negative value for ***x*** is:\n",
    "\n",
    "\\begin{equation}x = \\frac{16 - 15.491933384829668}{4}\\;\\;\\;\\;=0.12701665379258298\\end{equation}\n",
    "\n",
    "\n",
    "\n",
    "The following Python code uses the vertex formula and the quadtratic formula to calculate the vertex and the -x and +x for y = 0, and then plots the resulting parabola:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_parabola_from_formula (a, b, c):\n",
    "    import math\n",
    "\n",
    "    # Get vertex\n",
    "    print('CALCULATING THE VERTEX')\n",
    "    print('vx = -b / 2a')\n",
    "\n",
    "    nb = -b\n",
    "    a2 = 2*a\n",
    "    print('vx = ' + str(nb) + ' / ' + str(a2))\n",
    "\n",
    "    vx = -b/(2*a)\n",
    "    print('vx = ' + str(vx))\n",
    "\n",
    "    print('\\nvy = ax^2 + bx + c')\n",
    "    print('vy =' + str(a) + '(' + str(vx) + '^2) + ' + str(b) + '(' + str(vx) + ') + ' + str(c))\n",
    "\n",
    "    avx2 = a*vx**2\n",
    "    bvx = b*vx\n",
    "    print('vy =' + str(avx2) + ' + ' + str(bvx) + ' + ' + str(c))\n",
    "\n",
    "    vy = avx2 + bvx + c\n",
    "    print('vy = ' + str(vy))\n",
    "\n",
    "    print ('\\nv = ' + str(vx) + ',' + str(vy))\n",
    "\n",
    "    # Get +x and -x (showing intermediate calculations)\n",
    "    print('\\nCALCULATING -x AND +x FOR y=0')\n",
    "    print('x = -b +- sqrt(b^2 - 4ac) / 2a')\n",
    "\n",
    "\n",
    "    b2 = b**2\n",
    "    ac4 = 4*a*c\n",
    "    print('x = ' + str(nb) + '+-sqrt(' + str(b2) + ' - ' + str(ac4) + ')/' + str(a2))\n",
    "\n",
    "    sr = math.sqrt(b2 - ac4)\n",
    "    print('x = ' + str(nb) + ' +- ' + str(sr) + ' / ' + str(a2))\n",
    "    print('-x = ' + str(nb) + ' - ' + str(sr) + ' / ' + str(a2))\n",
    "    print('+x = ' + str(nb) + ' + ' + str(sr) + ' / ' + str(a2))\n",
    "\n",
    "    posx = (nb + sr) / a2\n",
    "    negx = (nb - sr) / a2\n",
    "    print('-x = ' + str(negx))\n",
    "    print('+x = ' + str(posx))\n",
    "\n",
    "\n",
    "    print('\\nPLOTTING THE PARABOLA')\n",
    "    import pandas as pd\n",
    "\n",
    "    # Create a dataframe with an x column a range of x values to plot\n",
    "    df = pd.DataFrame ({'x': range(round(vx)-10, round(vx)+11)})\n",
    "\n",
    "    # Add a y column by applying the quadratic equation to x\n",
    "    df['y'] = a*df['x']**2 + b*df['x'] + c\n",
    "\n",
    "    # get min and max y values\n",
    "    miny = df.y.min()\n",
    "    maxy = df.y.max()\n",
    "\n",
    "    # Plot the line\n",
    "    %matplotlib inline\n",
    "    from matplotlib import pyplot as plt\n",
    "\n",
    "    plt.plot(df.x, df.y, color=\"grey\")\n",
    "    plt.xlabel('x')\n",
    "    plt.ylabel('y')\n",
    "    plt.grid()\n",
    "    plt.axhline()\n",
    "    plt.axvline()\n",
    "\n",
    "    # Plot calculated x values for y = 0\n",
    "    plt.scatter([negx, posx],[0,0], color=\"green\")\n",
    "    plt.annotate('-x=' + str(negx) + ',' + str(0),(negx, 0), xytext=(negx - 3, 5))\n",
    "    plt.annotate('+x=' + str(posx) + ',' + str(0),(posx, 0), xytext=(posx - 3, -10))\n",
    "\n",
    "    # plot the line of symmetry\n",
    "    sx = [vx, vx]\n",
    "    sy = [miny, maxy]\n",
    "    plt.plot(sx,sy, color='magenta')\n",
    "\n",
    "    # Annotate the vertex\n",
    "    plt.scatter(vx,vy, color=\"red\")\n",
    "    plt.annotate('v=' + str(vx) + ',' + str(vy),(vx, vy), xytext=(vx - 1, vy - 10))\n",
    "\n",
    "    plt.show()\n",
    "    \n",
    "\n",
    "plot_parabola_from_formula (2, -16, 2)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.6",
   "language": "python",
   "name": "python36"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
